<template>
  <div class="message-error-handler">
    <!-- 消息状态指示器 -->
    <div class="message-status-indicator" v-if="showStatusIndicator">
      <el-tooltip :content="getStatusTooltip()" placement="top">
        <div class="status-icon" :class="getStatusClass()">
          <el-icon v-if="message.messageStatus === 'sending'">
            <Loading />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'queued'">
            <Clock />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'sent'">
            <Check />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'delivered'">
            <CircleCheck />
          </el-icon>
          <el-icon v-else-if="message.messageStatus === 'failed'">
            <Close />
          </el-icon>
        </div>
      </el-tooltip>
    </div>

    <!-- 错误处理操作 -->
    <div class="error-actions" v-if="message.messageStatus === 'failed'">
      <el-button 
        type="danger" 
        size="small" 
        :loading="retrying"
        @click="handleRetry"
      >
        <el-icon><Refresh /></el-icon>
        重试 ({{ retryCount }}/3)
      </el-button>
      
      <el-button 
        type="info" 
        size="small" 
        @click="showErrorDetails = true"
      >
        <el-icon><InfoFilled /></el-icon>
        详情
      </el-button>
    </div>

    <!-- 队列状态详情 -->
    <div class="queue-status" v-if="showQueueStatus && queueInfo">
      <div class="queue-info">
        <span class="queue-label">队列:</span>
        <el-tag 
          :type="getQueueTagType()" 
          size="small"
        >
          {{ getQueueStatusText() }}
        </el-tag>
        
        <span class="routing-strategy" v-if="queueInfo.routingStrategy">
          路由: {{ queueInfo.routingStrategy }}
        </span>
      </div>
      
      <div class="queue-timing" v-if="queueInfo.queuedAt">
        <span class="timing-label">入队:</span>
        <span class="timing-value">{{ formatTime(queueInfo.queuedAt) }}</span>
        
        <span class="timing-label" v-if="queueInfo.processedAt">处理:</span>
        <span class="timing-value" v-if="queueInfo.processedAt">
          {{ formatTime(queueInfo.processedAt) }}
        </span>
      </div>
    </div>

    <!-- 错误详情对话框 -->
    <el-dialog
      v-model="showErrorDetails"
      title="消息发送错误详情"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="error-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="消息ID">
            {{ message.id }}
          </el-descriptions-item>
          <el-descriptions-item label="发送状态">
            <el-tag :type="getStatusTagType()">
              {{ getStatusText() }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="重试次数">
            {{ retryCount }}/3
          </el-descriptions-item>
          <el-descriptions-item label="路由策略" v-if="queueInfo?.routingStrategy">
            {{ queueInfo.routingStrategy }}
          </el-descriptions-item>
          <el-descriptions-item label="入队时间" v-if="queueInfo?.queuedAt">
            {{ formatFullTime(queueInfo.queuedAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="处理时间" v-if="queueInfo?.processedAt">
            {{ formatFullTime(queueInfo.processedAt) }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="error-actions-dialog">
          <el-button 
            type="primary" 
            :loading="retrying"
            @click="handleRetry"
            :disabled="retryCount >= 3"
          >
            <el-icon><Refresh /></el-icon>
            重新发送
          </el-button>
          
          <el-button @click="showErrorDetails = false">
            关闭
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Loading, 
  Clock, 
  Check, 
  CircleCheck, 
  Close, 
  Refresh, 
  InfoFilled 
} from '@element-plus/icons-vue'
import { useTeamChatStore } from '@/stores/teamChat'
import type { TeamMessageDTO, QueueInfo } from '@/api/teamMessage'

// Props
interface Props {
  message: TeamMessageDTO
  showStatusIndicator?: boolean
  showQueueStatus?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  showStatusIndicator: true,
  showQueueStatus: false
})

// Store
const teamChatStore = useTeamChatStore()

// 响应式数据
const showErrorDetails = ref(false)
const retrying = ref(false)

// 计算属性
const queueInfo = computed((): QueueInfo | null => {
  return teamChatStore.getMessageQueueInfo(props.message.id)
})

const retryCount = computed((): number => {
  return queueInfo.value?.retryCount || 0
})

// 方法
const getStatusClass = () => {
  const status = props.message.messageStatus
  return {
    'status-sending': status === 'sending',
    'status-queued': status === 'queued',
    'status-sent': status === 'sent',
    'status-delivered': status === 'delivered',
    'status-failed': status === 'failed'
  }
}

const getStatusTooltip = (): string => {
  const status = props.message.messageStatus
  const statusMap = {
    sending: '正在发送...',
    queued: '已进入队列，等待处理',
    sent: '发送成功',
    delivered: '已投递',
    failed: `发送失败 (重试 ${retryCount.value}/3)`
  }
  return statusMap[status] || '未知状态'
}

const getStatusText = (): string => {
  const status = props.message.messageStatus
  const statusMap = {
    sending: '发送中',
    queued: '队列中',
    sent: '已发送',
    delivered: '已投递',
    failed: '发送失败'
  }
  return statusMap[status] || '未知'
}

const getStatusTagType = () => {
  const status = props.message.messageStatus
  const typeMap = {
    sending: 'info',
    queued: 'warning',
    sent: 'success',
    delivered: 'success',
    failed: 'danger'
  }
  return typeMap[status] || 'info'
}

const getQueueTagType = () => {
  const status = props.message.messageStatus
  if (status === 'failed') return 'danger'
  if (status === 'delivered') return 'success'
  if (status === 'sent') return 'success'
  if (status === 'queued') return 'warning'
  return 'info'
}

const getQueueStatusText = (): string => {
  const status = props.message.messageStatus
  if (status === 'failed') return '处理失败'
  if (status === 'delivered') return '已投递'
  if (status === 'sent') return '已发送'
  if (status === 'queued') return '队列中'
  return '处理中'
}

const formatTime = (timestamp: number): string => {
  const now = Date.now()
  const diff = now - timestamp
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  
  return new Date(timestamp).toLocaleString()
}

const formatFullTime = (timestamp: number): string => {
  return new Date(timestamp).toLocaleString()
}

const handleRetry = async () => {
  if (retrying.value || retryCount.value >= 3) return
  
  retrying.value = true
  
  try {
    const success = await teamChatStore.retryFailedMessage(props.message.id)
    if (success) {
      ElMessage.success('正在重新发送消息...')
      showErrorDetails.value = false
    }
  } catch (error) {
    console.error('重试消息失败:', error)
    ElMessage.error('重试失败，请稍后再试')
  } finally {
    retrying.value = false
  }
}
</script>

<style scoped lang="scss">
.message-error-handler {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.message-status-indicator {
  .status-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    
    &.status-sending {
      color: #409eff;
      animation: spin 1s linear infinite;
    }
    
    &.status-queued {
      color: #e6a23c;
    }
    
    &.status-sent {
      color: #67c23a;
    }
    
    &.status-delivered {
      color: #67c23a;
    }
    
    &.status-failed {
      color: #f56c6c;
    }
  }
}

.error-actions {
  display: flex;
  gap: 4px;
  
  .el-button {
    padding: 4px 8px;
    font-size: 12px;
  }
}

.queue-status {
  font-size: 12px;
  color: #666;
  
  .queue-info {
    display: flex;
    align-items: center;
    gap: 4px;
    margin-bottom: 2px;
  }
  
  .queue-timing {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .timing-label {
      color: #999;
    }
    
    .timing-value {
      color: #666;
    }
  }
}

.error-details {
  .error-actions-dialog {
    margin-top: 20px;
    text-align: right;
    
    .el-button {
      margin-left: 8px;
    }
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}
</style>
